import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../net/api_service.dart';
import '../../../net/httpsClient.dart';
import '../../../services/utils.dart';
import '../models/update_post_entity.dart';

class EditPostController extends GetxController {
  // 文章信息
  String postId = '';
  String originalTitle = '';
  String originalContent = '';
  int originalState = 1;

  // 表单控制器
  final titleController = TextEditingController();
  final contentController = TextEditingController();

  // 响应式数据
  final isLoading = false.obs;
  final isPublished = true.obs; // true: 发布, false: 草稿

  @override
  void onInit() {
    super.onInit();
    // 获取传递的文章信息
    final arguments = Get.arguments;
    if (arguments != null) {
      postId = arguments['postId']?.toString() ?? '';
      originalTitle = arguments['title']?.toString() ?? '';
      originalContent = arguments['content']?.toString() ?? '';
      originalState = arguments['state'] ?? 1;

      // 设置初始值
      titleController.text = originalTitle;
      contentController.text = originalContent;
      isPublished.value = originalState == 1;

      myLog('编辑文章初始化 - ID: $postId, 标题: $originalTitle');
    }
  }

  @override
  void onClose() {
    titleController.dispose();
    contentController.dispose();
    super.onClose();
  }

  // 更新文章
  Future<void> updatePost() async {
    final title = titleController.text.trim();
    final content = contentController.text.trim();

    if (title.isEmpty) {
      SmartDialog.showToast('请输入文章标题');
      return;
    }

    if (content.isEmpty) {
      SmartDialog.showToast('请输入文章内容');
      return;
    }

    if (postId.isEmpty) {
      SmartDialog.showToast('文章ID不能为空');
      return;
    }

    isLoading.value = true;
    SmartDialog.showLoading(msg: "更新中...");

    try {
      final request = UpdatePostRequest(
        id: postId,
        title: title,
        content: content,
        state: isPublished.value ? 1 : 0,
      );

      myLog('更新文章请求: ${request.toJson()}');

      final response = await HttpsClient()
          .post(ApiService.updatePost, data: request.toJson());

      if (response == null || response.data == null) {
        SmartDialog.showToast('更新失败，请重试');
        return;
      }

      final entity = UpdatePostEntity.fromJson(response.data);
      myLog('更新文章响应: ${response.data}');

      if (entity.code == 100 && entity.data == true) {
        SmartDialog.showToast(
          '文章更新成功！',
          alignment: Alignment.center,
        );

        myLog('文章更新成功');

        // 延迟一下让用户看到成功提示，然后返回并传递更新的数据
        await Future.delayed(const Duration(milliseconds: 1500));

        // 返回更新的文章信息
        Get.back(result: {
          'success': true,
          'title': title,
          'content': content,
          'state': isPublished.value ? 1 : 0,
        });
      } else {
        SmartDialog.showToast(
          entity.message ?? '更新失败',
          alignment: Alignment.center,
        );
      }
    } catch (e, stackTrace) {
      myLog('更新文章失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast('更新失败: $e');
    } finally {
      isLoading.value = false;
      SmartDialog.dismiss();
    }
  }

  // 切换发布状态
  void togglePublishStatus() {
    isPublished.value = !isPublished.value;
  }

  // 重置表单
  void resetForm() {
    titleController.text = originalTitle;
    contentController.text = originalContent;
    isPublished.value = originalState == 1;
  }

  // 检查是否有修改
  bool get hasChanges {
    return titleController.text.trim() != originalTitle ||
        contentController.text.trim() != originalContent ||
        (isPublished.value ? 1 : 0) != originalState;
  }
}
